package com.douya.security.config;

import com.douya.security.filter.JwtAuthenticationTokenFilter;
import com.douya.security.property.DouYaSecurityProperties;
import com.douya.security.utils.JwtUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * Security权限校验
 *
 * @author hcy
 * @date 2021-11-21 10:49
 */
@Configuration
@EnableWebSecurity
//@ConditionalOnProperty(prefix = "douya.security", name = "enable", havingValue = "true")
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
@ConditionalOnClass(org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class)
public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Resource
    UserDetailsService userDetailsService;

    @Resource
    DouYaSecurityProperties mSecurityProperties;

    @Resource
    RedissonClient mRedissonClient;

    @Resource
    JwtUtils jwtUtil;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 禁用 CSRF，因为我们使用的是 JWT
                .csrf().disable()
                // Spring Security 不会创建或使用 session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                // 允许访问静态资源
                .antMatchers(HttpMethod.GET, staticResourcesUri()).permitAll()
                // 允许匿名访问认证端点
                .antMatchers(nonAuthUri()).permitAll()
                // 其他所有请求都需要认证
                .anyRequest().authenticated().and()
//                // 自定义 403 响应
//                .exceptionHandling().authenticationEntryPoint(new SimpleAuthenticationEntryPoint()).and()
                // 在 UsernamePasswordAuthenticationFilter 之前添加 JWT 过滤器
                .addFilterBefore(new JwtAuthenticationTokenFilter(
                        userDetailsService,
                        mSecurityProperties,
                        mRedissonClient,
                        jwtUtil
                ), UsernamePasswordAuthenticationFilter.class)
                // 禁用框架选项以允许 H2 控制台
                .headers().frameOptions().disable()
                // 禁用缓存
                .cacheControl();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.userDetailsService)
                // 使用BCrypt进行密码的hash
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(nonAuthUri());
    }

    /**
     * 不需要权限校验的静态资源
     *
     * @return 静态资源
     */
    private String[] staticResourcesUri() {
        boolean enabled = mSecurityProperties.isEnable();
        String[] staticResourcesUri;
        if (!enabled) {
            // 关闭权限校验
            staticResourcesUri = new String[]{"/**"};
        } else {
            staticResourcesUri = mSecurityProperties.getStaticResourcesUri();
        }
        return staticResourcesUri;
    }

    /**
     * 不需要权限校验的uri
     *
     * @return uri
     */
    private String[] nonAuthUri() {
        boolean enabled = mSecurityProperties.isEnable();
        String[] nonAuthUri;
        if (!enabled) {
            // 关闭权限校验
            nonAuthUri = new String[]{"/**"};
        } else {
            nonAuthUri = mSecurityProperties.getNonAuthUri();
        }
        return nonAuthUri;
    }
}
